package com.cyys.common.utils.jwt;

import java.security.Key;
import java.util.Date;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * Created by ThinkPad on 2017/6/17.
 */
@Component
public class JwtUtil {
	public static String sercetKey = "mingtianhenganghao";
	public final static long keeptime = 1800000;

	/*
	 * @Value("${token.sercetKey}") public static String sercetKey;
	 * 
	 * @Value("${token.keeptime:30000}") public static long keeptime;
	 */

	public static String generToken(String id, String issuer, String subject) {
		long ttlMillis = keeptime;
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);
		byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(sercetKey);
		Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

		JwtBuilder builder = Jwts.builder().setId(id).setIssuedAt(now);
		if (subject != null) {
			builder.setSubject(subject);
		}
		if (issuer != null) {
			builder.setIssuer(issuer);
		}
		builder.signWith(signatureAlgorithm, signingKey);

		if (ttlMillis >= 0) {
			long expMillis = nowMillis + ttlMillis;
			Date exp = new Date(expMillis);
			builder.setExpiration(exp);
		}
		return builder.compact();
	}

	public String updateToken(String token) {
		try {
			Claims claims = verifyToken(token);
			String id = claims.getId();
			String subject = claims.getSubject();
			String issuer = claims.getIssuer();
			claims.getExpiration();
			return generToken(id, issuer, subject);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return "0";
	}

	public String updateTokenBase64Code(String token) {
		try {
			
			token = new String(Base64.decodeBase64(token), "utf-8");
			Claims claims = verifyToken(token);
			String id = claims.getId();
			String subject = claims.getSubject();
			String issuer = claims.getIssuer();
			claims.getExpiration();
			String newToken = generToken(id, issuer, subject);
			return Base64.encodeBase64String(newToken.getBytes());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return "0";
	}

	public static Claims verifyToken(String token) {
		Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(sercetKey))
				.parseClaimsJws(token).getBody();
		return claims;
	}
}
